/*
cache and session are defined here

*/
package session

import (
	"web/cookie"
	"web/redi"

	"net/http"
	"strconv"
)

var cookey string
var sessionLapse int

//Cookey  设置cookie秘钥
func Cookey(hs string) {
	cookey = hs
}

//Lapse  设置session过期时间
//lapse 时间
func Lapse(lapse int) {
	sessionLapse = lapse
}

//Init 用户登录后第一次设置session
func Init(user string, role, dept int) {
	redi.Set(user+"role", strconv.Itoa(role), sessionLapse)
	redi.Set(user+"dept", strconv.Itoa(dept), sessionLapse)

}

//Set
// k:key v:value pwd: secure string for secure cookie
func Set(r *http.Request, k, v string) (ok bool) {
	us, ok := cookie.SecureCookie(r, "user", cookey)
	if ok {
		redi.Set(us+k, v, sessionLapse)
	}
	return

}

//Get
func Get(r *http.Request, k string) (s string, ok bool) {
	s, ok = cookie.SecureCookie(r, "user", cookey)

	if ok {
		s, err := redi.Get(s + k)
		return s, err == nil
	}
	return "", false

}

//Cache age :cache的有效期
// 第一个s 为key，第二个为value
func Cache(age int, s ...string) (string, bool) {

	if len(s) == 1 {
		r, err := redi.Get("cache_" + s[0])
		return r, err == nil && len(r) > 0

	}
	if len(s) == 2 {
		redi.Set("cache_"+s[0], s[1], age)

	}
	return "", true

}
